#include "suggest.h"
#include "ui_suggest.h"
#include "databasemanager.h"
#include "session.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QDebug>

suggest::suggest(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::suggest)
{
    ui->setupUi(this);
    loadVenues();
}

suggest::~suggest()
{
    delete ui;
}

void suggest::loadVenues()
{
    ui->comboBoxVenue->clear();
    QSqlQuery query(DatabaseManager::instance().getDatabase());
    if (!query.exec("SELECT venue_id, name FROM Venues ORDER BY name")) {
        qDebug() << "加载场馆列表失败：" << query.lastError().text();
        return;
    }

    while (query.next()) {
        int id = query.value("venue_id").toInt();
        QString name = query.value("name").toString();
        ui->comboBoxVenue->addItem(name, id);
    }
}

void suggest::on_pushButtonSubmit_clicked()
{
    int visitorId = Session::getVisitorId();
    if (visitorId < 0) {
        QMessageBox::warning(this, "错误", "未登录或用户信息异常，无法提交推荐。");
        return;
    }

    int venueId = ui->comboBoxVenue->currentData().toInt();
    QString suggestion = ui->textEditSuggestion->toPlainText().trimmed();
    QString strategy = ui->textEditStrategy->toPlainText().trimmed();

    if (suggestion.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入推荐理由。");
        return;
    }

    QSqlQuery query(DatabaseManager::instance().getDatabase());
    query.prepare("INSERT INTO Venue_Recommendations (venue_id, visitor_id, suggestion, strategy) "
                  "VALUES (:venueId, :visitorId, :suggestion, :strategy)");
    query.bindValue(":venueId", venueId);
    query.bindValue(":visitorId", visitorId);
    query.bindValue(":suggestion", suggestion);
    query.bindValue(":strategy", strategy);

    if (!query.exec()) {
        QMessageBox::warning(this, "提交失败", "保存推荐信息失败：" + query.lastError().text());
        return;
    }

    QMessageBox::information(this, "成功", "感谢您的推荐！");
    ui->textEditSuggestion->clear();
    ui->textEditStrategy->clear();
}
